package tools;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public final class SerializationTool {

    private SerializationTool() {}
	
    public static void encodeToXMLFile(Object object, String fileName) throws FileNotFoundException, IOException {
        XMLEncoder encoder = new XMLEncoder(new FileOutputStream(fileName));
        try {
            encoder.writeObject(object);
            encoder.flush();
        } finally {
            encoder.close();
        }
    }
    
    public static Object decodeFromXMLFile(String fileName) throws FileNotFoundException, IOException {
        Object object = null;
        XMLDecoder decoder = new XMLDecoder(new FileInputStream(fileName));
        try {
            object = decoder.readObject();
        } finally {
            decoder.close();
        }
        return object;
    }

    
    public static void encodeToBinaryFile(Object object, String fileName) throws FileNotFoundException, IOException {
		ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(fileName));
		try {
			oos.writeObject(object); 
			oos.flush();
		} finally {
			oos.close();
		}
    }
    
    /**
     * Deserialisation d'un objet depuis un fichier
     * @param filename chemin du fichier
     */
    public static Object decodeFromBinaryFile(String fileName) throws FileNotFoundException, IOException {
        Object object = null;

		ObjectInputStream ois= new ObjectInputStream(new FileInputStream(fileName));
		try {	
			object = ois.readObject(); 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ois.close();
		}
		return object;
    }
}